//app.js
const call = require('/utils/request.js');
const util = require('/utils/util.js');
const md5 = require('/utils/md5.js')
App({
  onLaunch: function() {
    // this._getToken();
    this.globalData.TotalNumber = 5;
    let that = this;
    // 展示本地存储能力
    var logs = wx.getStorageSync('logs') || []
    logs.unshift(Date.now())
    wx.setStorageSync('logs', logs)
    //云开发
    if (!wx.cloud) {
      console.error('请使用 2.2.3 或以上的基础库以使用云能力')
    } else {
      wx.cloud.init({
        traceUser: true,
        env: 'unilife-bzlbj'
      })
    }

    // 登录
    wx.login({
      success: res => {
        // 发送 res.code 到后台换取 openId, sessionKey, unionId
      }
    })
    // 获取用户信息
    wx.getSetting({
      success: res => {
        if (res.authSetting['scope.userInfo']) {
          // 已经授权，可以直接调用 getUserInfo 获取头像昵称，不会弹框
          wx.getUserInfo({
            success: res => {
              // 可以将 res 发送给后台解码出 unionId
              this.globalData.userInfo = res.userInfo

              // 由于 getUserInfo 是网络请求，可能会在 Page.onLoad 之后才返回
              // 所以此处加入 callback 以防止这种情况
              if (this.userInfoReadyCallback) {
                this.userInfoReadyCallback(res)
              }
            }
          })
        }
      }
    })

    //获取页面的有关信息
    wx.getSystemInfo({
      success: function(res) {
        var sWidth = res.windowWidth;
        var sHeight = res.windowHeight;
        that.globalData.sWidth = sWidth;
        that.globalData.sHeight = sHeight;
      },
    });
  },
  globalData: {
    userId: null,
    phoneNumber: null,
    openId: null,
    userInfo: null,
    access_token: null,
    mac: null,
    TotalNumber: 0, // 购物车数量
    userPosition: {},
    foodmanager: {
      activeCabin: '冷藏室'
    },
    reqHeader: {}
  },
  _getToken() { //获取token
    let that = this;
    return new Promise(resolve => {
      const url = '/service/access?grant_type=client_credentials&client_id=unilife_standard_api_haier&client_secret=unilife_standard_api_haier_123456';
      call.postData(url, {},
        res => {
          resolve(res.access_token);
        },
        err => {
          console.log('获取token失败');
          wx.showModal({
            title: '获取token失败',
            icon: 'none'
          })
        });
    });
  },
  _getOpenId() { //获取openId
    let that = this;
    return new Promise(resolve => {
      wx.login({
        success(reslogin) {
          if (reslogin.code) {
            wx.getUserInfo({
              success(res) {
                // console.log('user',res)
                that.globalData.userInfo = res.userInfo;
                const url = '/service/app/v1/account/decodeWxUserInfo'; //根据encryptedData,iv,code获取openId
                const params = {
                  "data": {
                    'encryptedData': res.encryptedData,
                    'iv': res.iv,
                    'code': reslogin.code
                  }
                }
                call.postData(url, params,
                  res => {
                    resolve(res.data.openId)
                  },
                  err => {
                    wx.showToast({
                      title: '获取openId失败',
                      icon: 'none'
                    })
                    console.log('获取openId失败', err)
                  })
              },
              fail() {
                wx.showToast({
                  title: '网络好像出小差了__getOpenId',
                  icon: 'none'
                })
              }
            })
          } else {
            console.log('登录失败！' + res.errMsg);
            wx.showToast({
              title: '登录失败',
              icon: 'none'
            })
          }
        }
      })
    });
  },
  _getPhoneNumber(openId) { //根据openId获取用户手机号码
    let that = this;
    return new Promise(resolve => {
      const url = `/service/app/v1/account/loginByOpenId`;
      const params = {
        "header": {},
        "data": {
          "openId": openId
        }
      };
      call.postData(url, params,
        res => {
          if (res.data.cellphone) { //已绑定手机号的用户
            resolve(res.data.cellphone)
          } else { //未绑定手机号的用户
            wx.setStorage({
              key: 'log',
              data: 'true',
            });
            wx.reLaunch({
              url: '../login/login'
            })
          }
        },
        err => {
          wx.showToast({
            title: '获取手机号失败',
            icon: 'none'
          })
          console.log('获取openId失败', err)
        })
    });

  },
  _getMac() {
    let that = this;
    return new Promise(resolve => {
      wx.getStorage({
        key: 'log',
        success: function(res) {
          wx.navigateTo({
            url: '../login/login',
          });
          resolve('')
        },
        fail() {
          that._getToken().then(res1 => {
            that._getOpenId().then(res2 => {
              that._getPhoneNumber(res2).then(res3 => {
                const url = `/service/app/v1/account/getUserBindDeviceInfo?access_token=${res1}`;
                const params = {
                  "data": {
                    "cellphone": res3
                  }
                };
                call.postData(url, params, res => {
                  console.log('获取mac接口调通', res);
                  if (res.data) {
                    that.globalData.mac = res.data.deviceCode;
                    resolve(res.data.deviceCode);

                    console.log('您的设备号为:', res.data.deviceCode);
                  } else {
                    wx.hideLoading() //隐藏加载框
                    that.globalData.mac = 'unilife' + that.globalData.phoneNumber
                    resolve('unilife' + that.globalData.phoneNumber)

                    console.log('您的测试设备号为:', 'unilife' + that.globalData.phoneNumber);
                  }
                }, err => {
                  wx.showToast({
                    title: '网络好像出小差了_getMac',
                    icon: 'none'
                  })
                });

                that.globalData.access_token = res1;
                that.globalData.openId = res2;
                that.globalData.phoneNumber = res3;
                that.globalData.reqHeader = {
                  "timestamp": util.dataFormat().time2,
                  "deviceCode": that.globalData.mac,
                  "ver": "v1.0",
                  "sign": md5.hexMD5(`timestamp:${util.dataFormat().time2},deviceCode:${that.globalData.mac},ver:v1.0,unilife`)
                }
              })
            })
          })
        }
      })
    });

  }
})